﻿namespace Away.Jobs.Services.Implements;

public class TriggerService : ITriggerService
{
    private readonly IScheduler _scheduler;
    private readonly ITriggerRepository _triggerRepository;
    public TriggerService(ISchedulerFactory schedulerFactory, ITriggerRepository triggerRepository)
    {
        _scheduler = AsyncHelper.RunSync(() => schedulerFactory.GetScheduler());
        _triggerRepository = triggerRepository;
    }

    public async Task<List<string>> GetTriggerGroupList()
    {
        return (await _scheduler.GetTriggerGroupNames()).ToList();
    }
    public ApiResult GetTriggerPage(TriggerSearch search)
    {
        return _triggerRepository.GetTriggerPage(search);
    }
    public Task AddTrigger(ITrigger trigger)
    {
        return _scheduler.ScheduleJob(trigger);
    }
    public async Task AddTrigger(TriggerModel model)
    {
        await _scheduler.ScheduleJob(model.Trigger);
    }
    public async Task UpdateTrigger(TriggerModel model)
    {
        await _scheduler.UnscheduleJob(model.Key);
        await _scheduler.ScheduleJob(model.Trigger);
    }
    public Task StartTrigger(string group)
    {
        return _scheduler.ResumeTriggers(GroupMatcher<TriggerKey>.GroupEquals(group));
    }
    public async Task StartTrigger(List<Key> keys)
    {
        var tasks = keys.Select(o => _scheduler.ResumeTrigger(o.TriggerKey)).ToArray();
        await Task.WhenAll(tasks);
    }
    public Task StopTrigger(string group)
    {
        return _scheduler.PauseTriggers(GroupMatcher<TriggerKey>.GroupEquals(group));
    }
    public async Task StopTrigger(List<Key> keys)
    {
        var tasks = keys.Select(o => _scheduler.PauseTrigger(o.TriggerKey)).ToArray();
        await Task.WhenAll(tasks);
    }
    public async Task DeleteTrigger(List<Key> keys)
    {
        var tasks = keys.Select(o => _scheduler.UnscheduleJob(o.TriggerKey)).ToArray();
        await Task.WhenAll(tasks);
    }

    public async Task RunTrigger(Key key)
    {
        var trigger = await _scheduler.GetTrigger(key.TriggerKey);
        if (trigger == null)
        {
            return;
        }
        await _scheduler.TriggerJob(trigger.JobKey, trigger.JobDataMap);
    }

}
